package com.example.pceb.utils;

import com.example.pceb.entity.OperationLog;
import com.example.pceb.service.OperationLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class OperationLogUtils {
    @Autowired
    private OperationLogService operationLogService;

    private static OperationLogService staticOperationLogService;

    @PostConstruct
    public void init() {
        staticOperationLogService = operationLogService;
    }

    /**
     * 记录操作日志
     * @param userId 用户ID
     * @param username 用户名
     * @param operationType 操作类型（如登录、信息修改、项目申请等）
     * @param operationDesc 操作描述
     * @param request HttpServletRequest（可为null）
     * @param method 方法名
     * @param params 参数
     * @param result 结果
     */
    public static void saveOperationLog(Long userId, String username, String operationType, String operationDesc,
                                        HttpServletRequest request, String method, String params, String result) {
        OperationLog log = new OperationLog();
        log.setUserId(userId);
        log.setUsername(username);
        log.setOperationType(operationType);
        log.setOperationDesc(operationDesc);
        log.setIp(getIp(request));
        log.setMethod(method);
        log.setParams(params);
        log.setResult(result);
        log.setCreateTime(new Date());
        staticOperationLogService.save(log);
    }

    private static String getIp(HttpServletRequest request) {
        if (request == null) return null;
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
} 